<template>
  <div>
    <section v-if="isLogin">

      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-icon name="delete" @click="clearCar" class="clear-car">清空</van-icon>

        <ul class="cate-left-list">
          <li v-for="(item, index) of carList" :key="item.pro_id">
            <van-swipe-cell>
              <div class="cate-left-item flex_r_b">
                <div class="cate-checkbox">
                  <van-checkbox v-model="item.ischeck" @change='singChange(index, item.ischeck)'></van-checkbox>
                </div>
                <div>
                  <img :src="item.pro_img" class="cate-left-item-img" />
                </div>
                <div class="flex_c" style="width: 70%">
                  <p>{{ item.pro_title }}</p>
                  <div class="flex_r_b_s">
                    <div class="price">￥{{ item.pro_price }}</div>
                    <div class="flex_r">
                      <!-- <van-icon name="delete" /> -->
                      <van-stepper :min="0" theme="round" button-size="22" disable-input @plus="goCar(item)"
                        @minus="goCar(item)" v-model="item.pro_num" />
                    </div>
                  </div>
                  <p class="pre_price">￥{{ item.pro_price }}</p>
                </div>
              </div>
              <!-- 删除按钮 -->
              <template #right>
                <van-button square text="删除" type="danger" class="delete-button" @click="deleteCar(item.pro_id)" />
              </template>
            </van-swipe-cell>
          </li>
        </ul>
      </van-pull-refresh>

      <van-submit-bar :price="totalPrice" button-text="提交订单" v-show="carList.length > 0" @submit="onSubmit">
        <van-checkbox v-model="checked" @change="isAll">全选</van-checkbox>
      </van-submit-bar>

      <div style="text-align: center" v-show="carList.length == 0">
        <img src="@/assets/img/l_empty.png" alt="" />
        <p>购物车空空如也</p>
      </div>
    </section>
    <section v-else>
      <van-button type="success">没有登录</van-button>
    </section>
  </div>
</template>


<script lang="ts" setup>
import { ref } from "vue";
import { showToast } from "vant";
import { httpGetToken } from "../../utils/request";
import router from "@/router";

// 定义购物车项的接口
interface CarItem {
  pro_id: number;
  pro_img: string;
  pro_title: string;
  pro_price: number;
  ischeck: boolean;
  pro_num: number
}

const carList = ref<CarItem[]>([]);
const checked = ref(true);
const isLogin = ref(true);
const refreshing = ref(false);
// 价格计算
const totalPrice = ref(0);
const onSubmit = () => {
  jsonObj()
  router.push("/confirm")
};


// const carList = ref([]);
// const checked = ref(false);
// const isLogin = ref(true);
// const refreshing = ref(false); // 定义 refreshing 变量
// const onSubmit = () => showToast("ok");
const singChange = (index: number, c: boolean) => {
  let price = 0;
  if (c == true) {
    carList.value[index].ischeck == true

  } else {
    carList.value[index].ischeck == false
  }

  const t = carList.value.every((item) => {
    return item.ischeck
  })
  // console.log(t)
  if (t == true) {
    checked.value = true
  } else {
    checked.value = false

  }
  jsPrice(index)
}

const jsPrice = (index?: number) => {
  let price = 0;
  // console.log(carList.value)
  carList.value.forEach((item: any) => {
    // 先把购物车选中的都加起来
    if (item.ischeck == true) {
        // console.log(Number(item.pro_price) * item.pro_num *100 )
        price += Number(item.pro_price) * item.pro_num *100
        // console.log(price)
        totalPrice.value = price
    }

  })




}
// 判断是否选中
const isAll = (c: boolean) => {
  // alert(c)
  if (c == true) {
    carList.value.forEach((item: any) => {
      item.ischeck = true
      
    })
  } else {
    carList.value.forEach((item: any) => {
      item.ischeck = false
      totalPrice.value = 0
    })
  }
}
//onRefresh方法
const onRefresh = () => {
  // 模拟加载状态
  refreshing.value = true;
  // 调用获取购物车数据的方法
  getCarList();
};


// 获取购物车数据   /api/car
const getCarList = () => {
  httpGetToken("/api/car", '', '').then((res: any) => {
    if (res.status === 200) {
      // 增加一个用于判断是否选中
      res.data.forEach((item: any) => {
        item.ischeck = true
      });
      carList.value = res.data
      refreshing.value = false; // 刷新完成后重置 refreshing
    }
  });
};
getCarList();

const goCar = (item: any) => {

}
//删除购物车  /api/car    delete    pro_id:商品id
const deleteCar = async (id: number) => {
  let res = await httpGetToken("/api/car", "delete", { pro_id: id });
  showToast({
    message: "删除购物车成功",
    duration: 1000,
  });
  // 刷新购物车
  getCarList();
}

// 清空购物车   /api/carAll   get token  clearCar
const clearCar = () => {
  httpGetToken("/api/carAll", "get", null).then((res: any) => {
    if (res.status === 200) {
      showToast({
        message: "清空购物车成功",
        duration: 1000,
      });
      getCarList();
    }
  });
};

// 存储json 带去下一个页面
const jsonObj = () =>{
  let obj:any = []
    carList.value.forEach((item:any) => {
        if(item.ischeck ==true){
            obj.push({
              pro_id:item.pro_id,
              pro_num:item.pro_num,
              pro_title:item.pro_title,
              pro_img:item.pro_img,
              pro_price:item.pro_price

            })
        }
    })
    localStorage.setItem('json',JSON.stringify(obj))
}
</script>




<style lang="less" scoped>
@active_color: #03a19c;

.flex_r {
  display: flex;

  align-items: center;
  // justify-content: space-between;
}

.flex_c_b {
  display: flex;
}

.flex_r_b {
  display: flex;
  //   justify-content: space-between;
  flex-direction: row;
  align-items: center;
}

.flex_r_b_s {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
}

.cate-left-list {
  background: #f5f5f5;
  padding: 20px;
  margin-bottom: 80px;

  li {
    background: #fff;
    border-radius: 20px;
    margin-bottom: 20px;
    padding: 20px;

    box-shadow: 0px 0px 30px #ededed;

    .cate-left-item-img {
      width: 140px;
      height: 160px;
      margin-right: 10px;
    }

    .price {
      color: #ff0000;
      font-weight: bold;
    }

    .pre_price {
      color: #999;
      font-size: 28px;
    }

    .cut {
      display: inline-block;
      border-radius: 50%;
      height: 40px;
      width: 40px;
      line-height: 40px;
      border: 2px solid #ededed;
      text-align: center;
      margin-right: 10px;
    }

    .add {
      display: inline-block;
      border-radius: 50%;
      height: 40px;
      line-height: 40px;
      width: 40px;
      border: 2px solid @active_color;
      text-align: center;
      margin-left: 10px;
    }
  }
}

.cate-checkbox {
  margin-right: 30px;
}

.clear-car {
  font-size: 30px;
  color: red;
  left: 640px;
  margin: 10px;
  cursor: pointer;
}

.delete-button {
  border-radius: 0 30px 30px 0;
  margin-left: 10px;
  width: 90%;
  height: 100%;
}
</style>